package com.epfresh.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.R;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.bean.HomeCommTag;
import com.epfresh.bean.OfferGoodsGo;
import com.epfresh.global.BaseApplication;
import com.epfresh.views.tag.TagCloudView;

import java.util.ArrayList;
import java.util.List;

import static android.view.View.GONE;

/**
 * Created by wzh on 2016/5/6.
 */
public class OfferGoGoodsAdapter extends BaseAdapter implements View.OnClickListener,View.OnFocusChangeListener {
    int selectPosition;
    @Override
    public void onFocusChange(View var1, boolean var2){
        if(var2){
            if(var1 instanceof EditText) {
                EditText et = (EditText) var1;
                selectPosition = et.getText().toString().length();
                et.setSelection(selectPosition);
            }
        }

    }

    public Context context;


    private List<OfferGoodsGo.ContentBean> list;
    private AdapterView.OnItemClickListener onAddClickListener;
    private String acceptTime;

    boolean isShowMarketName;

    OnCartAddListener onCartAddListener;
    OnCartAddListener onCollectListener;

    boolean dcFlag = true;


    public OfferGoGoodsAdapter(Context context, List<OfferGoodsGo.ContentBean> list) {
        this.context = context;
        this.list = list;
    }

    public OfferGoGoodsAdapter(Context context, List<OfferGoodsGo.ContentBean> list, boolean dcFlag) {
        this.context = context;
        this.list = list;
        this.dcFlag = dcFlag;
    }

    public OnCartAddListener getOnCartAddListener() {
        return onCartAddListener;
    }

    public void setOnCartAddListener(OnCartAddListener onCartAddListener) {
        this.onCartAddListener = onCartAddListener;
    }

    public OnCartAddListener getOnCollectListener() {
        return onCollectListener;
    }

    public void setOnCollectListener(OnCartAddListener onCollectListener) {
        this.onCollectListener = onCollectListener;
    }

    public boolean isShowMarketName() {
        return isShowMarketName;
    }

    public void setShowMarketName(boolean showMarketName) {
        isShowMarketName = showMarketName;
    }

    public String getAcceptTime() {
        return acceptTime;
    }

    public void setAcceptTime(String acceptTime) {
        this.acceptTime = acceptTime;
    }

    public boolean isShowTime() {
        return !(acceptTime == null || "".equals(acceptTime));
    }


    public AdapterView.OnItemClickListener getOnAddClickListener() {
        return onAddClickListener;
    }

    public void setOnAddClickListener(AdapterView.OnItemClickListener onAddClickListener) {
        this.onAddClickListener = onAddClickListener;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }
    public int nowPosition;
    boolean firstTouch;
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder vh = null;
        if (view == null) {
            vh = new ViewHolder();
            view = LayoutInflater.from(context).inflate(R.layout.item_offer_go, null, false);
//            vh.tvType = (TextView) view.findViewById(R.id.tv_type);
            vh.vLineTop = view.findViewById(R.id.v_line_top);
            vh.tvTitle = (TextView) view.findViewById(R.id.tv_product_title);
            vh.tvStore = view.findViewById(R.id.tv_store);
            vh.tvPreTitle = (TextView) view.findViewById(R.id.tv_pre_product_title);
            vh.tvMarketName = (TextView) view.findViewById(R.id.tv_market_name);
            vh.tvTime = (TextView) view.findViewById(R.id.tv_accept_time);

            vh.tvUnitPackage = (TextView) view.findViewById(R.id.tv_unit_package);
            vh.iv = (ImageView) view.findViewById(R.id.iv_product);
            vh.ivAdd = (ImageView) view.findViewById(R.id.iv_add);
            vh.tvCountAdd = (TextView) view.findViewById(R.id.ed_price);
            vh.countAddUnderlineLayout = view.findViewById(R.id.item_center_search_underline_layout);
            vh.countAddUnderlineTv = view.findViewById(R.id.item_center_search_ed_price_underline);
            vh.tvChargeNumber = (TextView) view.findViewById(R.id.tv_charge_number);
            vh.ivCountAdd = (ImageView) view.findViewById(R.id.iv_add_count);
            vh.ivCountRemove = (ImageView) view.findViewById(R.id.iv_remove_count);

            vh.ivCorner = (ImageView) view.findViewById(R.id.iv_corner);
            vh.tag = (TagCloudView) view.findViewById(R.id.ll_tags);
            vh.vCartBg = view.findViewById(R.id.v_cart_bg);
            vh.vContent = view.findViewById(R.id.order_ll);

            vh.rlMsg = view.findViewById(R.id.rl_msg);
            vh.edRequireContent = (EditText) view.findViewById(R.id.ed_require_content);
            vh.vFlag = view.findViewById(R.id.iv_msg);
            vh.vArrow = view.findViewById(R.id.tv_msg_right);
            vh.ivCollect = view.findViewById(R.id.iv_collect);

            vh.tv_price = (TextView) view.findViewById(R.id.tv_price);
/*            vh.tv_price_ = (TextView) view.findViewById(R.id.tv_price_);
            vh.tv_price_old = (TextView) view.findViewById(R.id.tv_price_old);*/
            vh.tv_activity_promotion = view.findViewById(R.id.tv_activity_promotion);
            vh.tv_activity_second = view.findViewById(R.id.tv_activity_second);
            vh.tvPromotionStatus = (TextView) view.findViewById(R.id.tv_promotion_status);

            vh.edRequireContent.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    //注意，此处必须使用getTag的方式，不能将position定义为final，写成mTouchItemPosition = position
                    nowPosition = (Integer) view.getTag();
                    firstTouch = true;
                    return false;
                }
            });
            vh.watcher = new EtTextChanged(i);
            vh.edRequireContent.addTextChangedListener(vh.watcher);

            view.setTag(vh);
        } else {
            vh = (ViewHolder) view.getTag();
        }
        vh.edRequireContent.setTag(i);

        if (nowPosition == i && firstTouch) {
            vh.edRequireContent.requestFocus();
            vh.edRequireContent.setSelection(vh.edRequireContent.getText().length());
        } else {
            vh.edRequireContent.clearFocus();
        }
        vh.watcher.setPosition(i);



        //vh.tv_price_old.setVisibility(GONE);
        vh.vCartBg.setTag(R.id.item_key_position, i);
        vh.vCartBg.setOnClickListener(this);
        vh.vContent.setTag(R.id.item_key_position, i);
        vh.vContent.setOnClickListener(this);
        vh.tvTitle.setTag(R.id.item_key_position, i);
        vh.tvTitle.setOnClickListener(this);
        OfferGoodsGo.ContentBean p = list.get(i);
        vh.tvStore.setText(p.getStoreName());
        ImageLoader.getInstance().displayImage(p.getThumbnail(), vh.iv);
        if ("2".equals(p.getType())) {//预售
            vh.tvPreTitle.setVisibility(View.VISIBLE);
            String html = "<font color=\"#00ffffff\">a预售】</font>" + p.getTitle();
            vh.tvTitle.setText(Html.fromHtml(html));
        } else {//现售
            vh.tvPreTitle.setVisibility(View.GONE);
            vh.tvTitle.setText(p.getTitle());
        }

        if (p.isAcceptOrders()) {
            vh.ivCountAdd.setImageResource(R.mipmap.price_add);

        } else {
            vh.ivCountAdd.setImageResource(R.mipmap.price_grey);
        }

        if (i == 0 && isShowTime()) {
            vh.tvTime.setVisibility(View.VISIBLE);
            vh.tvTime.setText(getAcceptTime());
        } else {
            vh.tvTime.setText("");
            vh.tvTime.setVisibility(View.GONE);
        }
        vh.edRequireContent.setText(p.getRequire());

        String goodsCount = p.getGoodsCount();
        vh.tv_price.setText(p.getPrice());
        /*vh.tv_price_.setText("元/" + p.getUnit());
        Double oldPrice = p.getOriginalPrice();

        if (oldPrice != p.getPriceOnly()) {
            vh.tv_price_old.setText(p.getOriginalPrice() + "元/" + p.getUnit());
            vh.tv_price_old.setVisibility(View.VISIBLE);
            vh.tv_price_old.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            if ("".equals(goodsCount)) {
                vh.tv_price_old.setVisibility(View.GONE);
            } else {
                vh.tv_price_old.setVisibility(View.VISIBLE);
            }
        } else {
            vh.tv_price_old.setVisibility(View.GONE);
        }*/
        if ("".equals(goodsCount)) {
            vh.showCartAddView(false);
        } else {
            vh.showCartAddView(true);
        }


        String promotionType = p.getPromotionItemType();

        if ("1".equals(promotionType)) {//1促销2秒杀
            vh.tv_activity_promotion.setVisibility(View.VISIBLE);
            vh.tv_activity_second.setVisibility(View.GONE);
        } else if ("2".equals(promotionType)) {//1促销2秒杀
            vh.tv_activity_promotion.setVisibility(View.GONE);
            vh.tv_activity_second.setVisibility(View.VISIBLE);
        } else {
            //vh.tv_price_old.setVisibility(View.GONE);

            vh.tv_activity_promotion.setVisibility(View.GONE);
            vh.tv_activity_second.setVisibility(View.GONE);
        }
        vh.edRequireContent.setOnFocusChangeListener(this);


        vh.tvCountAdd.setText(goodsCount);
        vh.countAddUnderlineTv.setText(goodsCount);
        vh.tvChargeNumber.setText("要货" + goodsCount + p.getChargeUnit());

        String pack = p.getPack();
        if (pack == null || "".equals(pack)) {
            vh.tvUnitPackage.setVisibility(View.INVISIBLE);
        } else {
            vh.tvUnitPackage.setVisibility(View.VISIBLE);
        }
        vh.tvUnitPackage.setText(pack);
        vh.ivAdd.setTag(R.id.item_key_position, i);
        vh.ivAdd.setOnClickListener(this);
        vh.ivAdd.setVisibility(View.GONE);
        vh.tvCountAdd.setTag(R.id.item_key_position, i);
        vh.ivCountAdd.setTag(R.id.item_key_position, i);
        vh.ivCollect.setTag(R.id.item_key_position, i);
        vh.ivCollect.setOnClickListener(this);
        vh.ivCountRemove.setTag(R.id.item_key_position, i);
        vh.iv.setTag(R.id.item_key_position, i);

        vh.rlMsg.setTag(R.id.item_key_position, i);
        vh.rlMsg.setOnClickListener(this);

        vh.tvCountAdd.setOnClickListener(this);
        vh.ivCountAdd.setOnClickListener(this);
        vh.ivCountRemove.setOnClickListener(this);
        vh.iv.setOnClickListener(this);
        ArrayList<HomeCommTag> tags = p.getTags();
        if (tags != null && tags.size() > 0) {
            vh.tag.setVisibility(View.VISIBLE);
        } else {
            vh.tag.setVisibility(View.GONE);

        }
        vh.tag.setCommTags(tags);
        String promotionMarkUrl = p.getPromotionMarkUrl();
        ImageLoader.getInstance().displayImage(promotionMarkUrl, new ImageViewAware(vh.ivCorner), BaseApplication.getTagOptions(promotionMarkUrl), null, null, null);
        String promotionItemStatus = p.getPromotionItemStatus();
//        WAITING(1, "待促销"), UNDERWAY(2, "促销中"), OVER(3, "促销结束"), SELL_OUT(4, "已抢光");
        if ("3".equals(promotionItemStatus)) {
            vh.tvPromotionStatus.setVisibility(View.VISIBLE);
            vh.tvPromotionStatus.setText("结束了");

            //vh.tvPromotion.setVisibility(View.INVISIBLE);
            vh.showPromotionView(false);
        } else if ("4".equals(promotionItemStatus)) {
            vh.tvPromotionStatus.setVisibility(View.VISIBLE);
            vh.tvPromotionStatus.setText("抢光了");
            vh.showPromotionView(false);
            //vh.tvPromotion.setVisibility(View.INVISIBLE);
        } else {
            vh.tvPromotionStatus.setVisibility(View.GONE);

        }
        vh.ivCollect.setVisibility(View.GONE);
/*        if (dcFlag) {  暂时有关这个属性隐藏掉
            vh.ivCollect.setVisibility(View.VISIBLE);
            if (p.isShow()) {
                vh.ivCollect.setImageResource(R.mipmap.icon_dc_collect);
            } else {
                vh.ivCollect.setImageResource(R.mipmap.icon_dc_un_collect);
            }
        } else {
            vh.ivCollect.setVisibility(View.GONE);
        }*/
        return view;
    }

    @Override
    public void onClick(View v) {
        Object o = v.getTag(R.id.item_key_position);

        if (o != null && o instanceof Integer) {
            int position = (int) o;
            if ((v.getId() == R.id.iv_add)) {

                if (onAddClickListener != null) {
                    onAddClickListener.onItemClick(null, v, position, position);
                }

            } else if (v.getId() == R.id.ed_price) {//购物车手动输入

                if (onCartAddListener != null && position < list.size()) {
                    onCartAddListener.onCartAdd(1, position, list.get(position), v);
                }

            } else if (v.getId() == R.id.iv_add_count) {//添加
                if (onCartAddListener != null && position < list.size()) {
                    if (list.get(position).isAcceptOrders())
                        onCartAddListener.onCartAdd(2, position, list.get(position), v);
                    else
                        Toast.makeText(context, "暂不接单", Toast.LENGTH_SHORT).show();
                }

            } else if (v.getId() == R.id.iv_remove_count) {//减少
                if (onCartAddListener != null && position < list.size()) {
                    onCartAddListener.onCartAdd(3, position, list.get(position), v);
                }

            } else if (v.getId() == R.id.tv_product_title || v.getId() == R.id.iv_product || v.getId() == R.id.order_ll) {//
                if (onCartAddListener != null && position < list.size()) {
                    onCartAddListener.onCartAdd(5, position, list.get(position), v);
                }

            } else if (v.getId() == R.id.v_cart_bg) {

            } else if (v.getId() == R.id.rl_msg) {
                onCartAddListener.onCartAdd(10, position, list.get(position), v);
            } else if (v.getId() == R.id.iv_collect) {

                if (onCollectListener != null && position < list.size()) {
                    onCollectListener.onCartAdd(-1, position, list.get(position), v);
                }
            }

        }
    }

    public interface OnCartAddListener {
        public void onCartAdd(int type, int position, OfferGoodsGo.ContentBean goods, View v);
    }

    public class ViewHolder {
        View vLineTop;
        TextView tvTitle;
        TextView tvStore;
        TextView tvPreTitle;
        TextView tvUnitPackage;
        TextView tvTime;
        TextView tvMarketName;
        ImageView iv;
        ImageView ivAdd;
        ImageView ivCountAdd;
        ImageView ivCountRemove;
        TextView tvCountAdd;
        TextView tvChargeNumber;
        TextView countAddUnderlineTv;
        /*        TextView tvPromotion;*/
        LinearLayout countAddUnderlineLayout;
        TextView tvPromotionStatus;
        ImageView ivCorner;
        ImageView ivCollect;
        View vCartBg;
        View vContent;
        View rlMsg;
        EditText edRequireContent;
        View vFlag;
        View vArrow;

        TextView tv_price, /*tv_price_, tv_price_old,*/ tv_activity_promotion, tv_activity_second;
        TagCloudView tag;
        EtTextChanged watcher;

        public void showCartAddView(boolean isShow) {
            if (isShow) {
                ivCountAdd.setVisibility(View.VISIBLE);
                ivCountRemove.setVisibility(View.VISIBLE);
                tvCountAdd.setVisibility(View.VISIBLE);
                countAddUnderlineLayout.setVisibility(View.VISIBLE);
                tvChargeNumber.setVisibility(View.VISIBLE);

                //tv_price_old.setVisibility(View.GONE);
                ivAdd.setVisibility(View.GONE);
                vLineTop.setVisibility(View.VISIBLE);
                rlMsg.setVisibility(View.VISIBLE);
                vFlag.setVisibility(View.VISIBLE);
/*                if (dcFlag) {
                    rlMsg.setVisibility(View.VISIBLE);
                    vFlag.setVisibility(View.VISIBLE);
                } else {
                    rlMsg.setVisibility(View.GONE);
                    vFlag.setVisibility(View.GONE);
                }*/
            } else {
                vLineTop.setVisibility(View.GONE);
                ivCountAdd.setVisibility(View.VISIBLE);
                ivCountRemove.setVisibility(View.GONE);
                tvCountAdd.setVisibility(View.GONE);
                countAddUnderlineLayout.setVisibility(View.GONE);
                //tv_price_old.setVisibility(View.VISIBLE);
                tvChargeNumber.setVisibility(View.GONE);
                rlMsg.setVisibility(View.GONE);
                vFlag.setVisibility(View.GONE);
                ivAdd.setVisibility(View.GONE);
            }
        }

        public void showPromotionView(boolean isShow) {
            if (isShow) {
                ivCountAdd.setVisibility(View.VISIBLE);
                ivCountRemove.setVisibility(View.VISIBLE);
                tvCountAdd.setVisibility(View.VISIBLE);
                countAddUnderlineLayout.setVisibility(View.VISIBLE);
                tvChargeNumber.setVisibility(View.VISIBLE);
                ivAdd.setVisibility(View.VISIBLE);
                if (dcFlag) {
                    rlMsg.setVisibility(View.VISIBLE);
                    vFlag.setVisibility(View.VISIBLE);
                } else {
                    rlMsg.setVisibility(View.GONE);
                    vFlag.setVisibility(View.GONE);
                }

            } else {
                ivCountAdd.setVisibility(View.GONE);
                ivCountRemove.setVisibility(View.GONE);
                tvCountAdd.setVisibility(View.GONE);
                countAddUnderlineLayout.setVisibility(View.GONE);
                tvChargeNumber.setVisibility(View.GONE);
                rlMsg.setVisibility(View.GONE);
                vFlag.setVisibility(View.GONE);
                ivAdd.setVisibility(View.GONE);
            }
        }


    }


    class EtTextChanged implements TextWatcher {
        private int position;

        public EtTextChanged(int position){
            this.position = position;
        }


        public void setPosition(int position) {
            this.position = position;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(TextUtils.isEmpty(s)) {
                writeContent.write(position,"");
                return;
            }
            writeContent.write(position,s.toString().trim());
        }
    }
    public interface WriteContent{
        void write(int position, String content);
    }
    private WriteContent writeContent;

    public WriteContent getWriteContent() {
        return writeContent;
    }

    public void setWriteContent(WriteContent writeContent) {
        this.writeContent = writeContent;
    }
}
